/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */

package com.startup.musicstore.services.Impl;

import com.startup.musicstore.domain.CreditCard;
import com.startup.musicstore.domain.Customer;
import com.startup.musicstore.domain.CustomerInvoice;
import com.startup.musicstore.domain.Order;
import com.startup.musicstore.respository.CustomerRepository;
import com.startup.musicstore.respository.OrderRepository;
import com.startup.musicstore.services.OrderService;
import java.util.ArrayList;
import java.util.List;
import org.springframework.beans.factory.annotation.Autowired;

/**
 *
 * @author 211202320
 */
public class OrderServiceImpl implements OrderService{
    
    @Autowired
    OrderRepository orderRepository;
    CustomerRepository customerRepository;
    
    @Override
    public List<Order> getPendingOrders() {
        List<Order> allOrders = orderRepository.findAll();
        return getPendingOrders(allOrders);
    }
    
    private List<Order> getPendingOrders(List<Order> orders)
    {
        List<Order> pendingOrders = new ArrayList<Order>();
        
        for(Order o : orders)
        {
            if(o.getCustomerInvoice().getInvoiceStatus() == "Pending")
                pendingOrders.add(o);
        }
        return pendingOrders;
    }

    @Override
    public List<Customer> customersWithPendingOrders()
    {
        List<Customer> allCustomers = customerRepository.findAll();
        List<Customer> customersWithPendingOrders = new ArrayList<Customer>();
        for(Customer c : allCustomers)
        {
            if(getPendingOrders(c.getOrders()).size() > 0)
            {
                customersWithPendingOrders.add(c);
            }
        }
        
        return customersWithPendingOrders;
    }
    
    @Override
    public void updateInvoiceStatus(CustomerInvoice customerInvoice)
    {
        List<Customer> allCustomers = customerRepository.findAll();
        
        for(Customer c : allCustomers)
        {
            List<Order> custOrders = orderRepository.findAll();
            
            for(Order o : custOrders)
            {
                if(o.getCustomerInvoice() == customerInvoice)
                {
                    List<CreditCard> cards = new ArrayList<CreditCard>();
                    
                    for(CreditCard cc : cards)
                    {
                        if(cc.getBalance().equals(customerInvoice.getOrderAmount()))
                        {
                            customerInvoice.setInvoiceStatus("PAID");
                            o.setCustomerInvoice(customerInvoice);
                            orderRepository.save(o);
                        }
                    }
                }
            }
        }
    }
    
}
